package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.Setmeal;
import com.itheima.dao.CategoryDao;
import com.itheima.exception.CustomException;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Tang
 * @date 2023/1/7
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void deleteCategory(Long categoryId) {

        //1.判断当前分类下是否存在菜品数据
        //1.1 构造查询条件，根据分类id查询菜品表
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId, categoryId);
        int count = dishService.count(dishWrapper);
        //1.2 如果存在数据，就直接返回删除失败
        if (count > 0) {
            throw new CustomException("该分类下存在菜品数据，无法删除！");
        }

        //2.判断当前分类下是否存在套餐数据
        //2.1 构造查询条件，根据分类id查询套餐表
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, categoryId);
        int count1 = setmealService.count(setmealWrapper);

        //2.2 如果存在数据，就直接返回删除失败
        if (count1 > 0) {
            throw new CustomException("该分类下存在套餐数据，无法删除！");
        }

        //3.调用父类的删除方法，Mp已经内置了删除方法
        this.removeById(categoryId);
    }

    @Override
    public int count(String name, Long id) {
        return categoryDao.count(name, id);
    }
}
